package edu.gdkm.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.gdkm.controller.dto.LoginDTO;
import edu.gdkm.controller.exception.ServiceException;
import edu.gdkm.controller.request.BaseRequest;
import edu.gdkm.controller.request.LoginRequest;
import edu.gdkm.controller.request.PasswordRequest;
import edu.gdkm.entity.Admin;
import edu.gdkm.mapper.AdminMapper;
import edu.gdkm.service.IAdminService;
import edu.gdkm.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class AdminService implements IAdminService {
    @Autowired
   private AdminMapper adminMapper;

    private static final String DEFAULT_PASS = "123";
    private static final String PASS_SALT = "hexin";
    /**
     * 查询全部
     * @return
     */
    @Override
    public List<Admin> list() {
        return adminMapper.list();
    }

    /**
     * 分页查询 模糊查询 PageHelper插件
     * @param userPageRequest
     * @return
     */
    @Override
    public PageInfo<Admin> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Admin> admin = adminMapper.listByCondition(baseRequest);
        return new PageInfo<>(admin);
    }

    /**
     * 新增用户
     */
    @Override
    public void save(Admin obj) {
        //默认密码123
        if (StrUtil.isBlank(obj.getPassword())){
            obj.setPassword(DEFAULT_PASS);

        }
        obj.setPassword(securePass(obj.getPassword()));//设置md5加密,加盐
        try{
            adminMapper.save(obj);
        }catch (DuplicateKeyException e){

                log.error("数据插入失败,username:{}",obj.getUsername());
                throw new ServiceException("用户名重复");

        }
    }


    /**
     * 通过id获取用户数据(修改用户)
     *
     * @return
     */
    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);

    }

    /**
     * 修改信息
     * @param admin
     * @return
     */
    @Override
    public void update(Admin admin) {
        admin.setUpdatetime(new Date());
        adminMapper.updateById(admin);

    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    /**
     * 登录
     * @param request
     */
    @Override
    public LoginDTO login(LoginRequest request) {
        Admin admin = null;
        try {
             admin = adminMapper.getByUsername(request.getUsername());
        }catch (Exception e){
            log.error("根据用户名{} 查询出错",request.getUsername());
            throw new ServiceException("用户名错误");
        }
        if (admin == null){
            throw new ServiceException("用户名或密码错误");
        }
        //判断密码是否合法
        String securePass = securePass(request.getPassword());
        if (!securePass.equals(admin.getPassword())){
            throw new ServiceException("用户名或密码错误");

        }
        if (!admin.isStatus()){
            throw new ServiceException("当前用户处于禁用状态,请联系管理员");

        }
        LoginDTO  loginDTO = new LoginDTO();
        BeanUtils.copyProperties(admin,loginDTO);

        //生成token
        String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword());
        loginDTO.setToken(token);
        return loginDTO;


    }

    /**
     * 修改密码
     * @param passwordRequest
     */
    @Override
    public void changePass(PasswordRequest request) {
        //对新的密码加密
        request.setNewPass(securePass(request.getNewPass()));
        int count = adminMapper.updatePassword(request);
        if (count <= 0){
            throw new ServiceException("修改密码失败");
        }

    }


    private String securePass(String password){
        return SecureUtil.md5(password+PASS_SALT);
    }
}
